package com.atguigu.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.*;

/**
 * @Author lzc
 * @Date 2022/4/14 14:03
 */
public class DwdLogApp extends BaseAppV1 {
    private final String START = "start";
    private final String DISPLAY = "display";
    private final String PAGE = "page";
    
    public static void main(String[] args) {
        new DwdLogApp().init("DwdLogApp", 2001, 1, "DwdLogApp", "DwdLogApp", "ods_log");
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        // 1. 纠正新老客户   巩固窗口, 还有状态的使用
        SingleOutputStreamOperator<JSONObject> validatedStream = validateNewOrOld(stream);
        // 2. 对数据进行分流: 启动 页面 曝光
        Map<String, DataStream<JSONObject>> threeStreams = splitStream(validatedStream);
        
        
        // 3. 把分流后的数据写入到Dwd , 每种日志一个topic
        writeToKafka(threeStreams);
        
    }
    
    private void writeToKafka(Map<String, DataStream<JSONObject>> streams) {
        streams
            .get(START)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_START));
        
        streams
            .get(DISPLAY)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_DISPLAY));
        streams
            .get(PAGE)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_PAGE));
        
    }
    
    private Map<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> stream) {
        
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>(PAGE) {};
        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>(DISPLAY) {};
        
        // 用到侧输出流
        /*
        主流: 启动
        侧1: 页面
        侧2: 曝光
         */
        SingleOutputStreamOperator<JSONObject> startStream = stream
            .process(new ProcessFunction<JSONObject, JSONObject>() {
                @Override
                public void processElement(JSONObject value,
                                           Context ctx,
                                           Collector<JSONObject> out) throws Exception {
                    if (value.containsKey("start")) {
                        // 是启动日志
                        out.collect(value); // 启动日志放入主流
                    } else {
                        // 页面日志
                        if (value.containsKey("page")) {
                            ctx.output(pageTag, value);
                        }
                        
                        // 曝光日志. 把曝光数据拍平
                        if (value.containsKey("displays")) {
                            JSONArray displays = value.getJSONArray("displays");
                            for (int i = 0; i < displays.size(); i++) {
                                JSONObject display = displays.getJSONObject(i);
                                
                                // 拍平之后补齐一些其他数据
                                display.putAll(value.getJSONObject("common"));
                                display.putAll(value.getJSONObject("page"));
                                display.put("ts", value.getLong("ts"));
                                
                                ctx.output(displayTag, display);
                            }
                        }
                    }
                }
            });
        
        DataStream<JSONObject> pageStream = startStream.getSideOutput(pageTag);
        DataStream<JSONObject> displayStream = startStream.getSideOutput(displayTag);
        
        // 如何返回3个流?
        // 返回List或者数组 可以
        // 返回map比较, 可以根据关键词来得到想要的流
        Map<String, DataStream<JSONObject>> result = new HashMap<>();
        result.put(START, startStream);
        result.put(PAGE, pageStream);
        result.put(DISPLAY, displayStream);
        return result;
    }
    
    private SingleOutputStreamOperator<JSONObject> validateNewOrOld(DataStreamSource<String> stream) {
        /*
        纠正新老客户度的原理?
         针对每个设备的第一条记录 is_new 是 1 其他的记录的都是0
         
         考虑到数据的乱序问题:
             1. 使用事件时间 + 水印 + 窗口
             
             2. 这个设置第一个窗口中, 时间戳最小的那个是 is_new 是1 , 其他的是 0
                如何识别出, 第一个窗口? 靠状态
             
             3. 非第一个窗口, 所有数据的is_new 应该都是 0
        
         */
        
        return stream
            .map(JSON::parseObject)  // 每条日志封装到一个JSONObect对象中
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {
                
                private ValueState<Long> firstWindowState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    firstWindowState = getRuntimeContext().getState(new ValueStateDescriptor<Long>("firstWindowState", Long.class));
                }
                
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<JSONObject> elements,
                                    Collector<JSONObject> out) throws Exception {
                    if (firstWindowState.value() == null) {
                        // 表示是第一个窗口
                        List<JSONObject> list = AtguiguUtil.toList(elements);
                        
                        // Collections.min(list, (o1, o2) -> o1.getLong("ts").compareTo(o2.getLong("ts")));
                        JSONObject min = Collections.min(list, Comparator.comparing(o -> o.getLong("ts")));
                        firstWindowState.update(min.getLong("ts"));//
                        
                        for (JSONObject element : list) {
                            if (element == min) {
                                element.getJSONObject("common").put("is_new", 1);
                            } else {
                                element.getJSONObject("common").put("is_new", 0);
                            }
                            out.collect(element);
                        }
                        
                    } else {
                        //不是第一个窗口, 每个数据的is_new都应该设置为0
                        
                        for (JSONObject element : elements) {
                            element.getJSONObject("common").put("is_new", 0);
                            out.collect(element);
                        }
                    }
                }
            });
        
        
    }
}
